<template>
  <div class="main-container">
    <!-- 条件搜索 -->
    <Condition>
      <div class="condition-item condition-item-3">
        <span class="condition-label">模块库名称</span>
        <el-input 
          class="condition-input" 
          v-model="conditionForm.name" 
          placeholder="请输入算法名称" 
        />
      </div>
      <!-- 算法平台 -->
      <!-- <div class="condition-item condition-item-3">
        <span class="condition-label">平台</span>
        <el-select 
          class="condition-input" 
          v-model="conditionForm.system" 
          placeholder="请选择算法平台"
          clearable
        >
          <el-option v-for="(item, index) in systems" :key="index" :label="item.name" :value="item.id" />
        </el-select>
      </div> -->
      <!-- <div class="condition-item condition-item-3">
        <span class="condition-label">状态</span>
        <el-select 
          class="condition-input" 
          v-model="conditionForm.status" 
          placeholder="请选择算法状态"
          clearable
        >
          <el-option v-for="(item, index) in taskStatus" :key="index" :label="item.label" :value="item.value" />
        </el-select>
      </div> -->
    </Condition>
    <!-- 数据表格部分 -->
    <div class="data-show">
      <!-- 头部操作按钮部分 -->
      <div class="data-actions">
        <span class="aniTxtBtn action" style="width: 120px;" @click="linkToCreate">新增模块库</span>
      </div>
      <!-- 底下表格 -->
      <div class="data-table">
        <!-- <el-table 
          border 
          stripe
          show-header
          v-loading="conditionForm.loading" 
          row-key="id"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :data="filterDatas"  
        > -->
        <el-table 
          border 
          stripe
          show-header
          v-loading="conditionForm.loading" 
          row-key="id"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :data="filterDatas"  
        >
          <el-table-column label="序号" align="center" type="index" width="100" />
          <el-table-column label="名称" align="center" prop="name"  />
          <el-table-column label="描述" show-overflow-tooltip align="center" prop="description">
            <template #default="{row}">
              {{ row.description ? row.description : '--' }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="280" fit>
            <template #default="{ row }">
              <div class="table-actions">
                <button class="aniTxtBtn red" @click="del(row)">删除</button>
              </div>
            </template>
          </el-table-column> 
          <!-- 没有数据时显示 -->
          <template #empty>
            <i class="iconfont icon-wushuju1 data-empty-icon"></i>
            <h3 class="data-empty">暂无数据</h3>
          </template>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script setup>
import * as moduleLibApi from '@/api/moduleLib.js';
import Condition from '@/components/common/Condition.vue';
import { ref, computed, onActivated } from 'vue';
import { useRouter } from 'vue-router';
import { api } from '@/utils/status.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { deepCopy } from '@/utils/utils.js';

// ============> data
const router = useRouter();
const systems = ref(api.common.systems);
const taskStatus = api.common.status;
const conditionForm = ref({
  loading: false,
  name: '',
  system: null,
  status: null
});
const datas = ref([]);
const flatDatas = ref([]);

// ============> computed
const getShow = computed(() => {
  return function (v, k, arr, returnKey) {
    let obj = arr.find((item) => item[k] === v);
    let res = obj ? obj[returnKey] : "--";
    return res;
  };
});
const filterDatas = computed(() => {
  if (conditionForm.value.name){
    let copyArr = deepCopy(flatDatas.value);
    let resultArr = [];
    copyArr.forEach(item => {
      if (item.name.includes(conditionForm.value.name)){
        item.name = getFindItemName(item.id).join(` / `);
        item.children = null;
        resultArr.push(item);
      }
    });
    return resultArr;
  }
  if (conditionForm.value.status !== null && conditionForm.value.status !== undefined && conditionForm.value.status !== ''){
    let copyArr = deepCopy(flatDatas.value);
    let resultArr = [];
    copyArr.forEach(item => {
      if (item.status === conditionForm.value.status){
        item.name = getFindItemName(item.id).join(` / `);
        item.children = null;
        resultArr.push(item);
      }
    });
    return resultArr;
  }
  if (conditionForm.value.system !== null && conditionForm.value.system !== undefined && conditionForm.value.system !== '') {
    let copyArr = deepCopy(flatDatas.value);
    let resultArr = [];
    copyArr.forEach(item => {
      if (item.system === conditionForm.value.system){
        item.name = getFindItemName(item.id).join(` / `);
        item.children = null;
        resultArr.push(item);
      }
    });
    return resultArr;
  }
  return datas.value;
});
// ============> hooks

// onMounted(() => {
//   getList();
// });

onActivated(() => {
  getList();
});

// ============> methods
// util
function getFindItemName(findId){
  let resultArr = [];
  getIdFromArr(findId, flatDatas.value, resultArr);
  function getIdFromArr(id, arr, result){
    let resultItem = arr.find(item => item.id === id);
    result.unshift(resultItem.name);
    if (resultItem.parentId !== '0') {
      getIdFromArr(resultItem.parentId, arr, result);
    }
  }
  return resultArr;
}
// util - 抻平数组
function flatArr(arr){
  let result = [];
  arr.forEach(item => {
    result.push(item);
    if (item.children && Array.isArray(item.children)){
      result.push(flatArr(item.children))
    }
  });
  return result.flat(Infinity);
}
function getList(){
  moduleLibApi.getModuleLibs()
    .then(res => {
      if (res && Array.isArray(res) && res.length > 0){
        datas.value = res;
        initDatas();
        flatDatas.value = flatArr(datas.value);
      }
    })
}
function initDatas(){
  if (Array.isArray(datas.value) && datas.value.length > 0){
    datas.value.forEach(item => {
      item.delFlag = false;
    });
  }
}
// 删除模块库
function del(item){
  // console.log(item)
  // if (item.delFlag){
  //   ElMessage.warning('当前正在执行删除，请稍后重试');
  //   return;
  // }
  // ElMessageBox.confirm('此操作将会删除该项及其所有子模块库，是否确认删除该项？', '警告', {
  //   confirmButtonText: '确定',
  //   cancelButtonText: '取消'
  // })
  //   .then(() => {
  //     item.delFlag = true;
  //     moduleLibApi.delModuleLib({
  //       id: item.id
  //     })
  //       .then(res => {
  //         // console.log(res);
  //         ElMessage.success('删除成功！');
  //         getList();
  //       })
  //       .catch(err => {
  //         console.log(err);
  //       })
  //       .finally(() => {
  //         item.delFlag = false;
  //       })
  //   })
  if (item.delFlag){
    ElMessage.warning('当前正在执行删除，请稍后重试');
    return;
  }
  ElMessageBox.confirm('此操作将会删除该项及其所有子模块库，是否确认删除该项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  })
    .then(async () => {
      try {
        item.delFlag = true;
        await moduleLibApi.delModuleLib({id: item.id});
        ElMessage.success('删除成功!');
        getList();
      } finally {
        item.delFlag = false;
      }
    })
}
function linkToCreate(){
  router.push({ name: 'moduleLibCreate'} );
}
</script>
<style lang='scss' scoped>
@import '@/assets/styles/mixin.scss';
.data-add {
  width: 100px;
}
.table-actions {
  display: flex;
  align-items: center;
  justify-content: space-around;
  width: 100%;
  height: 100%;
  .action {
    width: 80px;
  }
}
.table-actions-column {
  width: 100%;
  flex-direction: column;
  .actions-column {
    width: 100%;
    display: flex;
    justify-content: space-around;
  }
}
.green {
  color: var(--color-green);
}
.red {
  color: var(--color-red);
  @include red-text-shadow;
}
.blue {
  color: var(--color-text-hover);
  @include blue-text-shadow;
}
.main-color {
  color: var(--color-main);
  @include main-text-shadow;
}
.condition-item-5 {
  width: 46%;
}
</style>